package com.penghaisoft.microwms.base.web.common;

import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.base.web.data.service.IBaseDictionaryService;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description Spring boot 启动后执行
 * @author luoteng
 * @date 2017年5月24日 下午4:22:45
 * @version 1.0
 */
@Component
@Slf4j
public class Init implements CommandLineRunner {

	@Autowired
	private IBaseDictionaryService baseDictionaryService;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;// spring-data-redis
	
	/**
	 * @Title run
	 * @Description springboot 启动后执行该方法
	 * @author luoteng
	 * @date 2017年5月24日:下午4:22:29
	 * @param args
	 * @throws Exception
	 */
	@Override
	public void run(String... args) throws Exception {
		log.info("redis Cache start load!");
		dicReload();
		log.info("redis Cache loaded!----加载字典");
	}

	/**
	 * @Title dicReload
	 * @Description 字典值加入到redis缓存中
	 * @author luoteng
	 * @date 2017年5月24日 下午4:22:38 void
	 */
	public void dicReload() {
		//只加载有效的字典
		BaseDictionary tmp = new BaseDictionary();
		tmp.setActiveFlag("1");
		List<BaseDictionary> list = baseDictionaryService.queryAllByCondition(tmp);
		Map<String, List<BaseDictionary>> map = new HashMap<String, List<BaseDictionary>>();
		for(BaseDictionary baseDictionary : list){
			String dicType = baseDictionary.getDicType();
			List<BaseDictionary> tmpList;
			if(map.containsKey(dicType)){
				tmpList = map.get(dicType);
			}else{
				tmpList = new ArrayList<BaseDictionary>();
			}
			tmpList.add(baseDictionary);
			map.put(dicType, tmpList);
		}

		stringRedisTemplate.delete(Constant.DICTIONARY_DICTYPE + "*");
		for (String key:map.keySet()){
			stringRedisTemplate.opsForValue().set(Constant.DICTIONARY_DICTYPE + key, JSONObject.toJSONString(map.get(key)));
		}
	}
}
